'''
Created on 2010-09-04

'''

from cPickle import dump
from cPickle import load
from lcboItem import lcboItem
from sqloader import sqlloader
import sys,os

class itemPickler(object):
    ''' An lcbo item pickler.
    This class pickles lcbo items but can also read them in from off the disk 
    and display them.
    
    '''


    def __init__(self,path):
        '''
        Default Constructor
        '''
        self.pickleFile = None #:The opened file object where data is pickled.
        self.path = path #:path to save / load pickled files
        
    def test(self):
        '''Class sanity test.
        A simple sanity test.
        
        '''
        self.pickleFile = open(self.path,'w')
        
        for i in range(10):
            dump(lcboItem('test',
                          'test',
                          'test',
                          'test',
                          'test',
                          'test',
                          'test'),
                          self.pickleFile)
        
        self.pickleFile.close()
        
        print self.loadItems()
        
    def pickleItem(self,item):
        ''' Pickle a single item.
        Write out a single lcbo item to the path passed into the constructor
        
        @param item: A single lcbo item.
        @type item: lcboItem 
        '''
        
        if self.pickleFile is None:
            self.pickleFile = open(self.path, 'w')
        
        dump(item,self.pickleFile)
    
    def loadItems(self):
        ''' Load pickled items off the disk. 
        @rtype: a list of lcboItems
        @return: a list of loaded lcboItems.
          
        '''
        if self.pickleFile is not None:
            self.pickleFile.close()
        
        self.pickleFile = open(self.path, 'r')
        
        items = []
        try:
            while True:
                items.append(load(self.pickleFile))
        except EOFError: #stop when the file has no more pickled files.
            pass
        return items

    def close(self):
        ''' Close the pickle file.
        Close the opened file for which pickled information is being written
        or read.
        
        '''
        
        if self.pickleFile is not None:
            self.pickleFile.close()
    
    def makeDataBase(self):
        ''' Create an sqlite3 database out of the loaded pickle files. '''
        sql = sqlloader(self.path)
        sql.setupLcboDatabase()
        sql.createLcboTables()
                                   
        for item in self.loadItems():
            sql.addLcboItem(item)
        sql.close()    

        
if __name__ == '__main__':
    
    if len(sys.argv) > 1 and os.access(sys.argv[1], os.F_OK|os.R_OK):
        a =  itemPickler(sys.argv[1])
        a.makeDataBase()
    else:
        print 'error loading pickle data, bad path.\n ' +\
        'Usage: itemPickler picklePath'
    #a.test()
    